package cn.tedu.account.tx;

import cn.tedu.account.entity.AccountMessage;
import cn.tedu.account.service.AccountService;
import cn.tedu.account.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Amos
 * @date 2022/4/29
 */

@RocketMQMessageListener(topic = "orderTopic", consumerGroup = "account-group")
@Component
@Slf4j
public class AccountConsumer implements RocketMQListener<String> {
    @Autowired
    private AccountService accountService;

    @Transactional
    @Override
    public void onMessage(String json) {
        // json转成AccountMessage
        AccountMessage am = JsonUtil.from(json, AccountMessage.class);
        // 调用业务方法扣减金额
        accountService.decrease(am.getUserId(), am.getMoney());
        log.info("扣减账户金额成功");
    }
}
